package com.dongan.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongan.pojo.File;
import com.dongan.pojo.Module;
import com.dongan.pojo.ModuleDetails;
import com.dongan.pojo.Users;
import com.dongan.service.FileService;
import com.dongan.service.ModuleDetailsService;
import com.dongan.service.ModuleService;
import com.dongan.service.impl.FileServiceImpl;
import com.dongan.service.impl.ModuleDetailsServiceImpl;
import com.dongan.service.impl.ModuleServiceImpl;
import com.dongan.utils.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author longTao
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/module")
@CrossOrigin
@Slf4j
public class ModuleController {
    @Resource
    private ModuleService service;

    @Resource
    private ModuleDetailsService moduleDetailsService;

    @Resource
    private FileService fileService;

    /**
     * 查询模块
     * @param pageSize
     * @param productName
     * @param checkTag
     * @param firstId
     * @param secondId
     * @param threeId
     * @param pageNum
     * @return
     */
    @GetMapping("/queryModule")
    @PreAuthorize("hasAuthority('/materialCompositionDesignSheetQuery')")
    public Object queryModule(String pageSize,String productName, String checkTag, String firstId, String secondId, String threeId, String pageNum) {
        QueryWrapper<Module> queryWrapper = new QueryWrapper<>();
        Page<Module> filePage = new Page<>();
        if (!StringUtils.isEmpty(firstId)) {
            queryWrapper.eq("FIRST_KIND_ID", Long.valueOf(firstId));
        }
        if (!StringUtils.isEmpty(checkTag)) {
            queryWrapper.eq("CHECK_TAG", checkTag);
        }
        if (!StringUtils.isEmpty(secondId)) {
            queryWrapper.eq("SECOND_KIND_ID", Long.valueOf(secondId));
        }
        if (!StringUtils.isEmpty(productName)) {
            queryWrapper.eq("PRODUCT_NAME", productName);
        }
        if (!StringUtils.isEmpty(threeId)) {
            queryWrapper.eq("THIRD_KIND_ID", Long.valueOf(threeId));
        }

        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "2";
        }
        filePage.setSize(Long.valueOf(pageSize));
        filePage.setCurrent(Long.valueOf(pageNum));
        Page<Module> page = service.page(filePage, queryWrapper);
        return new ResultResponseUtil(true,page);
    }

    /**
     * 添加物料表
     * @param map
     * @return
     */
    @PostMapping("/addModule")
    @PreAuthorize("hasAuthority('/designSheetOfDesignatedMaterialComposition')")
    public Object addModule(@RequestBody Map<String,Object> map) {
        Module module=null;
        List<ModuleDetails> moduleDetails=null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            String s = mapper.writeValueAsString(map.get("module"));
            System.out.println("s = " + s);
            module= mapper.readValue(s, Module.class);
            String str=mapper.writeValueAsString(map.get("moduleDetails"));
            System.out.println("str = " + str);
            moduleDetails = mapper.readValue(str, new TypeReference<List<ModuleDetails>>() {
            });
            for (Object detail : moduleDetails) {
                System.out.println("detail = " + detail);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("module = " + module);
        //设计编号 DESIGN_ID
        String designID = 200 + NumberFormatUtil.numberFormat2(4, SerialNumber.moduleSN);
        module.setDesignId(designID);
        //CHECK_TAG S001-0
        module.setCheckTag("S001-0");
        //CHANGE_TAG B002-0
        module.setChangeTag("B002-0");
        //设计人
        Users users = (Users) CommonProp.user;
        module.setDesigner(users.getLoginId());
        BigDecimal priceSum = new BigDecimal(0);
        module.setCostPriceSum(priceSum);
        try {
            service.insertModule(module,moduleDetails);
            return new ResultResponseUtil(true,"添加成功!");
        }catch (Exception e){
            e.printStackTrace();
            return new ResultResponseUtil(false, "添加失败!");
        }



    }

    /**
     * 审核
     * @param module
     * @return
     */
    @PostMapping("/checkModule")
    @PreAuthorize("hasAuthority('/materialCompositionDesignSheetReview')")
    public Object checkModule(@RequestBody Module module) {
        module.setCheckTime(GetSysDateTime.getDatetime());
        Users users= (Users) SerialNumber.user;
        module.setChecker(users.getLoginId());
        boolean flag = service.updateById(module);
        if (!"S001-1".equals(module.getCheckTag())) {
            File file = new File();
            file.setId(Long.valueOf(module.getProductId()));
            file.setDesignModuleTag("W001-0");
            fileService.updateById(file);
            UpdateWrapper<ModuleDetails> wrapper=new UpdateWrapper<>();
            wrapper.eq("PARENT_ID",module.getId());
            moduleDetailsService.update(wrapper);
        }

        return new ResultResponseUtil(true, "已审核!");
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("queryModuleById")
    @PreAuthorize("hasAuthority('/materialCompositionDesignSheetQuery')")
    public Object queryModuleById(Long id) {
        QueryWrapper<Module> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("PRODUCT_ID",id);
        Module module =service.getOne(queryWrapper2);
       if (module==null){
           return new ResultResponseUtil("你母亲死了");
       }
        QueryWrapper<ModuleDetails> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID",module.getId());
        List<ModuleDetails> list = moduleDetailsService.list(queryWrapper);
        Map<String,Object> map=new HashMap<>();
        map.put("module",module);
        map.put("list",list);
        return new ResultResponseUtil(true, "查询成功!", map);
    }

    /**
     * 修改
     * @param map
     * @return
     */
    @PostMapping("/updateModule")
    @PreAuthorize("hasAuthority('/materialCompositionDesignOrderChange')")
    public Object updateModule(@RequestBody Map<String, Object> map) {
        Module module = null;
        List<ModuleDetails> moduleDetails = null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            module=mapper.readValue(mapper.writeValueAsString(map.get("module")),Module.class);
            moduleDetails=mapper.readValue
                    (mapper.writeValueAsString(map.get("moduleDetails")),new TypeReference<List<ModuleDetails>>(){});

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
     //   System.out.println("module = " + module);
/*        for (ModuleDetails detail : moduleDetails) {
            System.out.println("detail = " + detail);
            detail.setParentId(module.getId());
        }*/
        //设计人
        Users users = (Users) CommonProp.user;
        module.setChanger(users.getLoginId());
        module.setChangeTag("B002-1");
        module.setCheckTag("S001-0");
        BigDecimal priceSum = new BigDecimal(0);
        for (int i = 0; i < moduleDetails.size(); i++) {
            int j=i+1;
            ModuleDetails m = moduleDetails.get(i);
            //物料序号
            m.setDetailsNumber(Long.valueOf(j));
            //小计
            m.setSubtotal(m.getCostPrice().multiply(BigDecimal.valueOf(m.getAmount())));
            m.setResidualAmount(m.getAmount());
            //总计
            priceSum = priceSum.add(m.getSubtotal());
        }
        module.setCostPriceSum(priceSum);
        UpdateWrapper<Module> moduleUpdateWrapper=new UpdateWrapper<>();
        moduleUpdateWrapper.eq("PRODUCT_ID",module.getProductId());
        boolean flag = service.update(module,moduleUpdateWrapper);
        if (flag) {
            QueryWrapper<ModuleDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PARENT_ID", module.getId());
            boolean flag2 = moduleDetailsService.remove(queryWrapper);
            if (flag2) {
                boolean flag3 = moduleDetailsService.saveBatch(moduleDetails);
                if(flag3){
                    return new ResultResponseUtil(true, "修改成功!");
            }

            }

        }
        return new ResultResponseUtil(false, "修改失败!");
    }

}

